package com.deer.wms.project.root.license.controller;

import com.deer.wms.project.root.license.WindowsServerInfos;
import com.deer.wms.project.root.license.LicenseCheckModel;
import com.deer.wms.project.root.license.server.LicenseCreator;
import com.deer.wms.project.root.license.server.LicenseCreatorParam;
import com.deer.wms.project.root.license.AbstractServerInfos;
import com.deer.wms.project.root.license.LinuxServerInfos;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author : wei
 * @description :
 * @since : 2021-06-10 11:48:45
 **/
@RestController
@RequestMapping("/license")
public class LicenseCreatorController {
    /**
     * 证书生成路径
     */
    @Value("${license.licensePath}")
    private String licensePath;

    /**
     * 获取服务器硬件信息
     * @param osName 操作系统类型，如果为空则自动判断
     * @return LicenseExtModel
     */
    @RequestMapping(value = "/getServerInfos", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public LicenseCheckModel getServerInfos(@RequestParam(value = "osName", required = false) String osName) {
        //操作系统类型
        if (StringUtils.isBlank(osName)) {
            osName = System.getProperty("os.name");
        }
        osName = osName.toLowerCase();

        AbstractServerInfos abstractServerInfos = null;

        //根据不同操作系统类型选择不同的数据获取方法
        if (osName.startsWith("windows")) {
            abstractServerInfos = new WindowsServerInfos();
        } else if(osName.startsWith("linux")) {
            abstractServerInfos = new LinuxServerInfos();
        }

        return Objects.requireNonNull(abstractServerInfos).getServerInfos();
    }

    /**
     * 生成证书
     * @param param 生成证书的参数
     * @return
     */
    @RequestMapping(value = "/generateLicense", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public Map<String, Object> generateLicense(@RequestBody(required = true) LicenseCreatorParam param) {
        HashMap<String, Object> resultMap = new HashMap<>(2);

        if (StringUtils.isBlank(param.getLicensePath())) {
            param.setLicensePath(licensePath);
        }
        LicenseCreator licenseCreator = new LicenseCreator(param);

        boolean result = licenseCreator.generateLicense();

        if (result) {
            resultMap.put("result", "ok");
            resultMap.put("msg", param);
        }else {
            resultMap.put("result", "error");
            resultMap.put("msg", "证书文件生成失败");
        }


        return resultMap;
    }



}
